package com.jie.other.jetpack.paging

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.paging.LoadState
import androidx.paging.LoadStateAdapter
import com.jie.commonlib.widget.recyclerview.BindingViewHolder
import com.jie.other.databinding.OtherAdapterLoadMoreBinding

/**
 * 底部加载更多、加载失败重试、无更多数据适配器
 */
class LoadMoreAdapter(private val retryListener : () -> Unit) : LoadStateAdapter<BindingViewHolder<OtherAdapterLoadMoreBinding>>() {
    override fun onBindViewHolder(
        holder: BindingViewHolder<OtherAdapterLoadMoreBinding>,
        loadState: LoadState
    ) {
        holder.viewBinding.llLoading.visibility = if (loadState is LoadState.Loading) {
            View.VISIBLE
        } else {
            View.GONE
        }
        holder.viewBinding.tvNoMoreData.visibility = if (loadState is LoadState.NotLoading
            && loadState.endOfPaginationReached){
            View.VISIBLE
        } else {
            View.GONE
        }
        holder.viewBinding.tvRetry.run {
            visibility = if (loadState is LoadState.Error) {
                View.VISIBLE
            } else {
                View.GONE
            }
            setOnClickListener {
                retryListener.invoke()
            }
        }
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        loadState: LoadState
    ): BindingViewHolder<OtherAdapterLoadMoreBinding> {
        val inflater = LayoutInflater.from(parent.context)
        return BindingViewHolder(OtherAdapterLoadMoreBinding.inflate(inflater, parent, false))
    }

    override fun displayLoadStateAsItem(loadState: LoadState): Boolean {
        return super.displayLoadStateAsItem(loadState)
                || (loadState is LoadState.NotLoading && loadState.endOfPaginationReached)
    }


}